# 网络请求模块
import requests

# html 解析模块
from lxml import etree
import json, os
from tqdm import tqdm


main_url = (
    "https://live.huya.com/liveHttpUI/getLiveList?iGid=4079&iPageNo=1&iPageSize=120"
)
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0",
}


# 请求主页
def request_index(url):
    # 请求主页，使用定义好的头信息来伪装
    result = requests.get(url=url, headers=headers)
    if result.status_code == 200:  # 200表示正常请求
        with open("huya.json", "w", encoding="utf-8") as f:
            json.dump(result.json(), f, indent="  ", ensure_ascii=False)


def parse_data():
    if not os.path.exists("./huya.json"):
        request_index(main_url)
    with open("huya.json", "r", encoding="utf-8") as f:
        data = json.load(f)["vList"]
        if data:
            urls = [{x["sNick"]: x["sScreenshot"]} for x in data]
            return download(data=urls)


def download(data):
    if not os.path.exists("./image"):
        os.mkdir("./image")
    with tqdm(total=len(data)) as pbar:
        for i in data:
            for k, v in i.items():
                pbar.set_description(k)
                re = requests.get(v, headers=headers)
                with open(f"./image/{k}.jpg", "wb") as f:
                    f.write(re.content)
                pbar.update(1)


parse_data()
